﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>个人考勤信息管理</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <link href="../../Content/fullcalendar.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/TemplateCSS.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/Attendance/attendance.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/ui.fullcalendar.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/fullcalendar.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-jtemplates.js" type="text/javascript"></script>
    <script type="text/javascript">


    var URL_PERSONAL_ATTENDANCE_INFO_LIST = '/attendance/PersonalAttendanceInfoListPerMonth';
    var URL_SIMPLEUSERINFO_BY_DEPTID = '/core/GetUserInfoInDept';

    //************* 常量定义



    var StaticResource = {
        'AttdendacneTypeResource': {
            'onDuty': '上班',
            'offDuty': '下班'
        },
        "YesOrNoTarget": {
            "false": "否",
            "true": "是",
            "False": "否",
            "True": "是"
        }
      
    };

    //var memberSelector = null;

    var cssList = ['fc-normal',
                   'fc-abnormal',
                   'fc-holiday',
                  ];



    var Super = {
        Calendar: null,
        TipAttendance: null,

        //data
        InfoForCalendarList: null,
        AttendanceInfoPerDayList :null,
        CurrentDate: null,
        TargetDate: null,
        _self: null,
        _isBinding: false,
        internalInit: function()
        {
            Super.Calendar = $('#calendar');
            Super.TipAttendance = $('#tip_AttendanceInfo');

            Super.pageInit();
            Super.dataInit();

        },

        pageInit:function()
        {
            EzTipsManager.addTipBox('#tip_Remind', 'tipRemind');
            EzTipsManager.addTipBox('#tip_AttendanceInfo', 'tipAttendanceInfo');
            EzTipsManager.showTipBox('tipRemind');

            $('#btnApply').click(function (){
                window.location.href = '/Attendance/PersonalAttendanceInfoPerDay?time=' + Super.TargetDate + '&isApplying=' + true;
            });
            $('#btnDetail').click(function (){
                window.location.href = '/Attendance/PersonalAttendanceInfoPerDay?time=' + Super.TargetDate;
            });
        },

        dataInit:function()
        {
            this.bindAttendanceTitleInfo();
            
            $('#calendar').fullCalendar({ 
                theme: true,
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: ''
                },
                editable: false,events: null
            });
            EzAccessor.doUpdateAttendanceInfoList(
                Super.CurrentDate,
                Super.bindCalendarInfoList);
        },

        bindAttendanceTitleInfo:function (){
            var currentUser = EzAccessor.getCurrentUser();
            var isHasPermisson = EzAccessor.getIsHasPermisson();
            var date= Date.fromEpoch(EzAccessor.getCurrentTime());
            
            Super.CurrentDate =  new Date(
			    date.getFullYear(),
			    date.getMonth() + 1,
			    0,
			    0,
			    0,
                0
            ).toEpoch();

            var title = currentUser.Name + "的考勤记录";
            $('#txtAttendanceTitle').html(title);
        },

        bindCalendarInfoList:function (e) {
            Super.InfoForCalendarList = e[0];
            Super.AttendanceInfoPerDayList= e[1];
            
            var attendanceInfoList = 
            DataConverterForfullcalendar
            .convertfullcalendar(Super.InfoForCalendarList, convertor);

            Super._isBinding = true;
            $('#calendar').empty();
            $('#calendar').fullCalendar({
                theme: true,
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: ''
                },
                editable: false,
                events: attendanceInfoList,
                viewDisplay: Super.viewChangedCallback,
                eventClick: Super.mouseClickEventCallback,
                eventAfterRender: Super.eventAfterRenderCallback,
                windowResize: Super.windowResizeCallback
            });        
            $('#calendar').fullCalendar('gotoDate',
                                         Date.fromEpoch(Super.CurrentDate).getFullYear(),
                                         Date.fromEpoch(Super.CurrentDate).getMonth()
                                        );            
            
            var height = $('.fc-grid table').height();
            adjustEventElementHeight(height);

            Super._isBinding = false;
        },
        viewChangedCallback:function (e){
            var calendarDate = ($('#calendar').fullCalendar('getDate'));
           
            var date = new Date(
                calendarDate.getFullYear(),
				calendarDate.getMonth() + 1,
                0,
                0,
                0,
                0
            ).toEpoch();

            if(date != Super.CurrentDate && !Super._isBinding){
                Super.CurrentDate = date;
                EzAccessor.doUpdateAttendanceInfoList(
                    Super.CurrentDate,
                    Super.bindCalendarInfoList);
            };

        },
        mouseClickEventCallback:function (eventData) {
            //清空原来的数据
            cleanTipData();
            //存储日期
            var attendanceDate = eventData.id;
            Super.TargetDate = attendanceDate;
            //更新时间标题
            var date = Date.fromEpoch(attendanceDate).toFullDate();
            $('#txtTitle').html(date + "&nbsp;" + "考勤详情:");
            //显示新数据
            var attendanceInfoTheDay = Super.getAttendanceInfoTheDay(attendanceDate);
            
            var ondutyStr = '<dd class="dd-attendance">{onduty}</dd>';
            var offdutyStr = '<dd class="dd-attendance">{offduty}</dd>';
            var leaveInfoStr = '<dd class="dd-leaveInfo">{leaveInfo}</dd>';
            var evaluationStr =  '<dd class="dd-evaluation">{evaluation}</dd>';
            var remarkStr = '<dd class="dd-remark">{remark}</dd>'
            
            //考勤记录
            if(getDutyStr(attendanceInfoTheDay.onDutyList, "onDuty") ==  "" 
                && getDutyStr(attendanceInfoTheDay.offDutyList, "offDuty") == ""){
                
                $('.dl-attendance').append('<dd class="dd-attendance">没有考勤记录</dd>');
            }else {
                ondutyStr = ondutyStr.replace("{onduty}", getDutyStr(attendanceInfoTheDay.onDutyList, "onDuty"));
                offdutyStr = offdutyStr.replace("{offduty}", getDutyStr(attendanceInfoTheDay.offDutyList, "offDuty"));    
                
                $('.dl-attendance').append(ondutyStr)
                $('.dl-attendance').append(offdutyStr);
            }
            
            //假期情况
            if(getLeaveInfoStr(attendanceInfoTheDay).length == 0 ) {
                $('.dl-leaveInfo').hide();    
            }else {
                leaveInfoStr = leaveInfoStr.replace("{leaveInfo}", getLeaveInfoStr(attendanceInfoTheDay));    
                $('.dl-leaveInfo').append(leaveInfoStr);
                $('.dl-leaveInfo').show();  
            }
            
            //考勤评估
            evaluationStr = evaluationStr.replace("{evaluation}", getEvaluationStr(attendanceInfoTheDay));
            $('.dl-evluationInfo').append(evaluationStr);
            
            //todo:
            //备注
            if(getRemarkStr(attendanceInfoTheDay).length != 0){
                remarkStr = remarkStr.replace("{remark}", getRemarkStr(attendanceInfoTheDay));
                $('.dl-remark').append(remarkStr);
                $('.dl-remark').show();
            }else {
                $('.dl-remark').hide();
            }

            //是否可以申请修改
            controlApplication(attendanceInfoTheDay);

            EzTipsManager.showTipBox('tipAttendanceInfo');      
        },
        getAttendanceInfoTheDay:function (attendanceDate) {
            var attendanceInfoTheDay = null;
            for(var key in Super.AttendanceInfoPerDayList){
                var dateTime = (Super.AttendanceInfoPerDayList[key].theDay);
                if(dateTime == attendanceDate){
                    attendanceInfoTheDay = Super.AttendanceInfoPerDayList[key];
                }
            }

            return attendanceInfoTheDay;
        },
        windowResizeCallback:function (view){
            var tableHeight = view.element[0].clientHeight;
            adjustEventElementHeight(tableHeight)
         },
    
   
        eventAfterRenderCallback :function (eventData, jsEvent, view){
            var attendanceDate = eventData.id; 
            var attendanceInfoTheDay = Super.getAttendanceInfoTheDay(attendanceDate);
            var _self=  view.eventElementsByID[attendanceDate][0];
            //改变背景颜色
            var color = $(_self).find('a').css( 'background-color' );
            $(_self).hover(function (){
                $(_self).css( {'background-color': '#dadada'} );
                $(_self).find('a').css( {'background-color': '#dadada'} );
                },
                function (){
                    $(_self).css( {'background-color': color} );
                    $(_self).find('a').css( {'background-color': color} );
                });

            //qtips   
            $(_self).qtip({
                content: function () {
                    return getAttendanceInfoStrTheDay(attendanceInfoTheDay);
                },
                position: {
                    my: 'bottom center',  
                    at: 'top center' 
                }
            });
        }
    };
    


    //************* URL常量




    var convertor = {

        "id": function (item) {
            return item.theDayInfo.Date;
        },
        "title": function (item) {
            var str = "";
            if(item.simpleEvaluationStatus.length != 0)
                str = str + item.simpleEvaluationStatus
            if(item.applyModifyStr.length != 0)
                str = str + "\n" + item.applyModifyStr;
            if(item.modifyHistoryStr!= 0)
                str = str + "\n" + item.modifyHistoryStr;
            
            return str;
        },
        "start": function (item) {
            var startTime = Date.fromEpoch(item.theDayInfo.Date);
            return startTime;

        },

        "allDay": function (item) {
            return true;
        },

        "className": function (item) {
            return item.evaluationClassName;
        }

    };



    //************* Accessor访问器

    var EzAccessor = {};

    if (ezmock.IS_MOCKED) {
        var mock_isHasPermisson = true;
        var mockEzAccessor = {
        };
        EzAccessor = mockEzAccessor;
    } else {
        var realEzAccessor = {
            'doUpdateAttendanceInfoList': function (time,callback) {
                $(document).ajaxBusy('begin');
                //清空数据
                $('#calendar').fullCalendar('removeEvents');
                $.getJSON(
                    URL_PERSONAL_ATTENDANCE_INFO_LIST,
                    { 'time': time },function(e){
                        callback(e);
                        $(document).ajaxBusy('end');
                    });
            },
            'getCurrentUser': function () {
                return <%= ViewData["CurrentUser"] %>;
            },
            'getDeptList': function () {
                return <%= ViewData["CurrentDeptList"] %>;
            },
            'getCurrentTime': function () {
                return <%= ViewData["CurrentTime"] %>;
            },
            'getIsHasPermisson': function () {
                return <%= ViewData["IsHasPermisson"] %>;
            },
        };

        EzAccessor = realEzAccessor;
    }

  
    ///adjustEventElementHeight
    function adjustEventElementHeight(tableHeight) {
       var elementHeight = (((tableHeight / 6) * 0.90) - 25) + 'px';

       $('.fc-event').each(function() {
            $(this).css({ 'height': elementHeight});
       });
    }


   
    function getAttendanceInfoStrTheDay(attendanceInfoTheDay){
        //考勤记录
        var ondutyStr = getDutyStr(attendanceInfoTheDay.onDutyList, "onDuty");
        var offdutyStr = getDutyStr(attendanceInfoTheDay.offDutyList, "offDuty");
        //当天的假期记录
        var leaveInfoStr = getLeaveInfoStr(attendanceInfoTheDay);
        //当天的考勤评估
        var evaluationStr = getEvaluationStr(attendanceInfoTheDay);
        //备注
        var remarkStr = getRemarkStr(attendanceInfoTheDay);

        return evaluationStr + ondutyStr + offdutyStr + leaveInfoStr;
    }

     function getDutyStr (infoList, infoType) {
        var dutyStr = "";
        if(infoList.length != 0){
            for(var key in infoList){
                infoStr = '<p>{infoType}: &nbsp;{actionTime}</p>';
                infoStr = infoStr.replace("{actionTime}" , Date.fromEpoch(infoList[key].ActionTime).toFullTime())
                                 .replace("{infoType}" , StaticResource.AttdendacneTypeResource[infoType]);
                dutyStr = dutyStr + infoStr;
            }
        }
        return dutyStr;
    }

    function cleanTipData() {
        $('.dd-attendance').each(function (){
            $(this).remove();
        });
        $('.dd-leaveInfo').each(function (){
            $(this).remove();
        });
        $('.dd-evaluation').each(function (){
            $(this).remove();
        });
        $('.dd-remark').each(function (){
            $(this).remove();
        });
    };

    function controlApplication(attendanceInfoTheDay) {
        if(attendanceInfoTheDay.isToday == false){
            if(attendanceInfoTheDay.canApplyModify == true){
                $('#liApply').show();
                $('#liApplied').hide();
            }else {
                $('#liApply').hide(); 
                $('#liApplied').show();
            }
        }else{
            $('#liApply').hide(); 
            $('#liApplied').hide();
        }
               
    };

    function getLeaveInfoStr (attendanceInfo){
        var leaveStr = "";
        if (attendanceInfo.leaveModel) {
            var leaveInfo = attendanceInfo.leaveModel.Leaves;
            for (var key in leaveInfo){
                    leaveStr = leaveStr + '<p>{leaveName}: &nbsp;{starTime} -- {endTime}</p>';
                    leaveStr = leaveStr.replace("{leaveName}" , leaveInfo[key].LeaveTypeName)
                                       .replace("{starTime}", Date.fromEpoch(leaveInfo[key].StartTime).toFullTime())
                                       .replace("{endTime}", Date.fromEpoch(leaveInfo[key].EndTime).toFullTime())            
                
                }
            }
        return leaveStr;
    }


    function getEvaluationStr(attendanceInfo){
        var evalutionStr = attendanceInfo.evaluationStatus;
        return evalutionStr;
    }

   

    function getRemarkStr(attendanceInfo) {
        var remarkStr = "";
        var remark = attendanceInfo.remarkInfo? attendanceInfo.remarkInfo.Remark : "";
        if(remark.length != 0){
            remarkStr =  '<span>{remark}</span>';  
            remarkStr = remarkStr.replace("{remark}", remark); 
        }

        return  remarkStr;
    }

    $(function () {
        Super.internalInit();
    });
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <div id="page-head" class="page-head">
        <img src="../../Content/icons/calendar_red.png" style="width: 48px; height: 48px;"
            alt="attendanceInfo" />
        <span id="txtAttendanceTitle" class="title"></span>
    </div>
    <div id="page-body">
        <div id="calendar" style="width: 100%;">
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
    <div id="shortcuts" class="box">
    </div>
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id='tip_Remind' style="display: none;">
        <h1>
            小贴士:</h1>
        <p class="indent">
        </p>
        <table style="margin-left: 4px;">
            <tr>
                <td>
                    <span style="display: block; background: #eaf5e1; width: 30px; height: 20px"></span>
                </td>
                <td>
                    正常 ( 工时满8小时 )
                </td>
            </tr>
            <tr>
                <td>
                    <span style="display: block; background: #f5e4e4; width: 30px; height: 20px"></span>
                </td>
                <td>
                    非正常 ( 工时不满8小时 )
                </td>
            </tr>
            <tr>
                <td>
                    <span style="display: block; background: #e8f5fa; width: 30px; height: 20px"></span>
                </td>
                <td>
                    假期 ( 不需要上班 )
                </td>
            </tr>
        </table>
    </div>
    <div id="tip_AttendanceInfo" style="display: none;" class="tip-attention">
        <h1 id="txtTitle">
        </h1>
        <div id="div-tip-attendanceInfo" class="indent tip-list">
            <dl class="dl-attendance">
                <dt class="dt-attendance">考勤记录:</dt>
            </dl>
            <dl class="dl-leaveInfo">
                <dt class="dt-leaveInfo">假期情况:</dt>
            </dl>
            <dl class="dl-evluationInfo">
                <dt class="dt-evluationInfo">考勤评估:</dt>
            </dl>
            <dl class="dl-remark">
                <dt class="dt-remark">考勤备注:</dt>
            </dl>
        </div>
        <div class="indent">
            <p id="liApply" style="display: none; margin-bottom: 5px;">
                <a id="btnApply" style="width: 100%;">申请修改考勤评估</a>
                <%--<script type="text/javascript">
                    $(function () {
                        $("#btnApply").button({
                            icons: {
                                primary: "ui-icon-pencil"
                            },
                            text: true
                        });
                    });
                </script>--%>
            </p>
            <p id="liApplied" style="display: none; ">
                <a id="btnDetail">
                    已经申请修改考勤评估，请等待处理 </a>
            </p>
        </div>
    </div>
</asp:Content>
